package stm.liyiruo.sign2pdf.util;

import java.io.*;
import java.util.Base64;

/**
 * @author liyiruo
 * @Description
 * @Date 2021/8/13 上午10:58
 */
public class PDFUtils {
    /**
     * 将文件读成base64
     *
     * @param pathStr
     * @return
     */
    public static String getBase64FromFile(String pathStr) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        FileInputStream is = null;
        try {
            is = new FileInputStream(pathStr);
            byte[] b = new byte[4096];
            int n = -1;
            while ((n = is.read(b)) != -1) {
                out.write(b, 0, n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        byte[] encode = Base64.getEncoder().encode(out.toByteArray());
        return new String(encode);
    }

    //把字节数组 写成文件
    public static void saveFile(String filename, byte[] data) throws Exception {
        if (data != null) {
            String filepath = filename;
            File file = new File(filepath);
            if (file.exists()) {
                file.delete();
            }
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data, 0, data.length);
            fos.flush();
            fos.close();
        }

    }
}
